package br.com.framework.app.bean;

import java.util.List;

import javax.enterprise.context.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import br.com.framework.app.model.Usuario;
import br.com.framework.app.negocio.api.UsuarioNegocio;
import br.com.framework.apresentacao.bean.BaseBean;
import br.com.framework.persistencia.sort.Order;

@Named
@SessionScoped
public class LoginBean extends BaseBean {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Inject
	private UsuarioNegocio usuarioNegocio;
	
	private Usuario usuario;
	
	/**
	 * @return
	 */
	public String login() {
		HttpServletRequest request = (HttpServletRequest) getExternalContext().getRequest();
		try {
		    request.login(usuario.getLogin(), usuario.getSenha());
		    return "/pages/protected/index.xhtml";
		} catch (ServletException e) {
			getFacesMessages().addMessageError(null, e.getMessage());
		    return "/pages/public/loginError.xhtml";
		}
	}
	
	/**
	 * @return
	 */
	public Usuario getUsuario() {
		if (usuario == null) {
			if (getExternalContext().getUserPrincipal() != null) {
				Usuario u = new Usuario();
				u.setLogin(getExternalContext().getUserPrincipal().getName());
				List<Usuario> list = usuarioNegocio.findByExample(u, -1, -1, "nome", Order.ASCENDING, false, true);
				if (list != null && list.size() == 1) {
					usuario = list.get(0);
				}
			}
		}
		return usuario;
	}

	/**
	 * @return
	 */
	public String logout() {
		ExternalContext exCont = getExternalContext();
		HttpServletRequest request = (HttpServletRequest) exCont.getRequest();
		request.getSession(false).invalidate();
		getFacesMessages().addMessageInfo(null, "login.usuario.sucessoLogout");
		return "/home.xhtml";
	}


}
